"""
定义导入导出的领域模型，屏蔽数据库细节。
"""
from __future__ import annotations

from dataclasses import dataclass, field
from datetime import datetime
from typing import List, Optional


@dataclass
class ParameterValueSnapshot:
    """单个参数值的快照"""

    index: Optional[int]
    value: Optional[str]
    id: Optional[int] = None
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None


@dataclass
class ParameterSnapshot:
    """参数及其值的封装"""

    name: str
    name_en: str
    param_type: str
    unit: Optional[str]
    description: Optional[str]
    is_list: bool
    is_year_related: bool
    list_length: Optional[int]
    sort_order: int
    values: List[ParameterValueSnapshot] = field(default_factory=list)
    id: Optional[int] = None
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None


@dataclass
class CategorySnapshot:
    """参数分类"""

    name: str
    name_en: str
    description: Optional[str]
    sort_order: int
    parameters: List[ParameterSnapshot] = field(default_factory=list)
    id: Optional[int] = None
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None


@dataclass
class ProjectMetadata:
    """项目元信息"""

    name: str
    name_en: str
    description: Optional[str]
    time_horizon: int
    start_year: int
    year_step: int
    end_year: int
    export_time: Optional[datetime] = None
    checksum: Optional[str] = None
    id: Optional[int] = None
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None


@dataclass
class ProjectSnapshot:
    """完整项目快照"""

    metadata: ProjectMetadata
    categories: List[CategorySnapshot] = field(default_factory=list)

    def ensure_export_time(self) -> None:
        if self.metadata.export_time is None:
            self.metadata.export_time = datetime.now()

